{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Word2Vec Tutorial\n",
    "\n",
    "In case you missed the buzz, word2vec is a widely featured as a member of the “new wave” of machine learning algorithms based on neural networks, commonly referred to as \"deep learning\" (though word2vec itself is rather shallow). Using large amounts of unannotated plain text, word2vec learns relationships between words automatically. The output are vectors, one vector per word, with remarkable linear relationships that allow us to do things like vec(“king”) – vec(“man”) + vec(“woman”) =~ vec(“queen”), or vec(“Montreal Canadiens”) – vec(“Montreal”) + vec(“Toronto”) resembles the vector for “Toronto Maple Leafs”.\n",
    "\n",
    "Word2vec is very useful in [automatic text tagging](https://github.com/RaRe-Technologies/movie-plots-by-genre), recommender systems and machine translation.\n",
    "\n",
    "Check out an [online word2vec demo](http://radimrehurek.com/2014/02/word2vec-tutorial/#app) where you can try this vector algebra for yourself. That demo runs `word2vec` on the Google News dataset, of **about 100 billion words**.\n",
    "\n",
    "## This tutorial\n",
    "\n",
    "In this tutorial you will learn how to train and evaluate word2vec models on your business data.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Preparing the Input\n",
    "Starting from the beginning, gensim’s `word2vec` expects a sequence of sentences as its input. Each sentence is a list of words (utf8 strings):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    }
   ],
   "source": [
    "# import modules & set up logging\n",
    "import gensim, logging\n",
    "logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:15,148 : INFO : collecting all words and their counts\n",
      "2017-06-29 10:36:15,149 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n",
      "2017-06-29 10:36:15,150 : INFO : collected 3 word types from a corpus of 4 raw words and 2 sentences\n",
      "2017-06-29 10:36:15,152 : INFO : Loading a fresh vocabulary\n",
      "2017-06-29 10:36:15,158 : INFO : min_count=1 retains 3 unique words (100% of original 3, drops 0)\n",
      "2017-06-29 10:36:15,159 : INFO : min_count=1 leaves 4 word corpus (100% of original 4, drops 0)\n",
      "2017-06-29 10:36:15,160 : INFO : deleting the raw counts dictionary of 3 items\n",
      "2017-06-29 10:36:15,167 : INFO : sample=0.001 downsamples 3 most-common words\n",
      "2017-06-29 10:36:15,168 : INFO : downsampling leaves estimated 0 word corpus (5.7% of prior 4)\n",
      "2017-06-29 10:36:15,169 : INFO : estimated required memory for 3 words and 100 dimensions: 3900 bytes\n",
      "2017-06-29 10:36:15,170 : INFO : resetting layer weights\n",
      "2017-06-29 10:36:15,172 : INFO : training model with 3 workers on 3 vocabulary and 100 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n",
      "2017-06-29 10:36:15,176 : INFO : worker thread finished; awaiting finish of 2 more threads\n",
      "2017-06-29 10:36:15,179 : INFO : worker thread finished; awaiting finish of 1 more threads\n",
      "2017-06-29 10:36:15,183 : INFO : worker thread finished; awaiting finish of 0 more threads\n",
      "2017-06-29 10:36:15,184 : INFO : training on 20 raw words (0 effective words) took 0.0s, 0 effective words/s\n",
      "2017-06-29 10:36:15,185 : WARNING : under 10 jobs per worker: consider setting a smaller `batch_words' for smoother alpha decay\n"
     ]
    }
   ],
   "source": [
    "sentences = [['first', 'sentence'], ['second', 'sentence']]\n",
    "# train word2vec on the two sentences\n",
    "model = gensim.models.Word2Vec(sentences, min_count=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Keeping the input as a Python built-in list is convenient, but can use up a lot of RAM when the input is large.\n",
    "\n",
    "Gensim only requires that the input must provide sentences sequentially, when iterated over. No need to keep everything in RAM: we can provide one sentence, process it, forget it, load another sentence…\n",
    "\n",
    "For example, if our input is strewn across several files on disk, with one sentence per line, then instead of loading everything into an in-memory list, we can process the input file by file, line by line:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# create some toy data to use with the following example\n",
    "import smart_open, os\n",
    "\n",
    "if not os.path.exists('./data/'):\n",
    "    os.makedirs('./data/')\n",
    "\n",
    "filenames = ['./data/f1.txt', './data/f2.txt']\n",
    "\n",
    "for i, fname in enumerate(filenames):\n",
    "    with smart_open.smart_open(fname, 'w') as fout:\n",
    "        for line in sentences[i]:\n",
    "            fout.write(line + '\\n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class MySentences(object):\n",
    "    def __init__(self, dirname):\n",
    "        self.dirname = dirname\n",
    " \n",
    "    def __iter__(self):\n",
    "        for fname in os.listdir(self.dirname):\n",
    "            for line in open(os.path.join(self.dirname, fname)):\n",
    "                yield line.split()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[['first'], ['sentence'], ['second'], ['sentence']]\n"
     ]
    }
   ],
   "source": [
    "sentences = MySentences('./data/') # a memory-friendly iterator\n",
    "print(list(sentences))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:18,159 : INFO : collecting all words and their counts\n",
      "2017-06-29 10:36:18,161 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n",
      "2017-06-29 10:36:18,162 : INFO : collected 3 word types from a corpus of 4 raw words and 4 sentences\n",
      "2017-06-29 10:36:18,163 : INFO : Loading a fresh vocabulary\n",
      "2017-06-29 10:36:18,164 : INFO : min_count=1 retains 3 unique words (100% of original 3, drops 0)\n",
      "2017-06-29 10:36:18,165 : INFO : min_count=1 leaves 4 word corpus (100% of original 4, drops 0)\n",
      "2017-06-29 10:36:18,166 : INFO : deleting the raw counts dictionary of 3 items\n",
      "2017-06-29 10:36:18,167 : INFO : sample=0.001 downsamples 3 most-common words\n",
      "2017-06-29 10:36:18,168 : INFO : downsampling leaves estimated 0 word corpus (5.7% of prior 4)\n",
      "2017-06-29 10:36:18,169 : INFO : estimated required memory for 3 words and 100 dimensions: 3900 bytes\n",
      "2017-06-29 10:36:18,170 : INFO : resetting layer weights\n",
      "2017-06-29 10:36:18,171 : INFO : training model with 3 workers on 3 vocabulary and 100 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n",
      "2017-06-29 10:36:18,183 : INFO : worker thread finished; awaiting finish of 2 more threads\n",
      "2017-06-29 10:36:18,184 : INFO : worker thread finished; awaiting finish of 1 more threads\n",
      "2017-06-29 10:36:18,185 : INFO : worker thread finished; awaiting finish of 0 more threads\n",
      "2017-06-29 10:36:18,186 : INFO : training on 20 raw words (0 effective words) took 0.0s, 0 effective words/s\n",
      "2017-06-29 10:36:18,186 : WARNING : under 10 jobs per worker: consider setting a smaller `batch_words' for smoother alpha decay\n"
     ]
    }
   ],
   "source": [
    "# generate the Word2Vec model\n",
    "model = gensim.models.Word2Vec(sentences, min_count=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Word2Vec(vocab=3, size=100, alpha=0.025)\n",
      "{'second': <gensim.models.keyedvectors.Vocab object at 0x7f1c573ce9d0>, 'first': <gensim.models.keyedvectors.Vocab object at 0x7f1c0d056b50>, 'sentence': <gensim.models.keyedvectors.Vocab object at 0x7f1c0d0569d0>}\n"
     ]
    }
   ],
   "source": [
    "print(model)\n",
    "print(model.wv.vocab)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Say we want to further preprocess the words from the files — convert to unicode, lowercase, remove numbers, extract named entities… All of this can be done inside the `MySentences` iterator and `word2vec` doesn’t need to know. All that is required is that the input yields one sentence (list of utf8 words) after another.\n",
    "\n",
    "**Note to advanced users:** calling `Word2Vec(sentences, iter=1)` will run **two** passes over the sentences iterator. In general it runs `iter+1` passes. By the way, the default value is `iter=5` to comply with Google's word2vec in C language. \n",
    "  1. The first pass collects words and their frequencies to build an internal dictionary tree structure. \n",
    "  2. The second pass trains the neural model.\n",
    "\n",
    "These two passes can also be initiated manually, in case your input stream is non-repeatable (you can only afford one pass), and you’re able to initialize the vocabulary some other way:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:19,845 : INFO : collecting all words and their counts\n",
      "2017-06-29 10:36:19,847 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n",
      "2017-06-29 10:36:19,848 : INFO : collected 3 word types from a corpus of 4 raw words and 4 sentences\n",
      "2017-06-29 10:36:19,849 : INFO : Loading a fresh vocabulary\n",
      "2017-06-29 10:36:19,849 : INFO : min_count=1 retains 3 unique words (100% of original 3, drops 0)\n",
      "2017-06-29 10:36:19,850 : INFO : min_count=1 leaves 4 word corpus (100% of original 4, drops 0)\n",
      "2017-06-29 10:36:19,851 : INFO : deleting the raw counts dictionary of 3 items\n",
      "2017-06-29 10:36:19,851 : INFO : sample=0.001 downsamples 3 most-common words\n",
      "2017-06-29 10:36:19,852 : INFO : downsampling leaves estimated 0 word corpus (5.7% of prior 4)\n",
      "2017-06-29 10:36:19,853 : INFO : estimated required memory for 3 words and 100 dimensions: 3900 bytes\n",
      "2017-06-29 10:36:19,853 : INFO : resetting layer weights\n",
      "2017-06-29 10:36:19,854 : INFO : training model with 3 workers on 3 vocabulary and 100 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n",
      "2017-06-29 10:36:19,856 : INFO : worker thread finished; awaiting finish of 2 more threads\n",
      "2017-06-29 10:36:19,857 : INFO : worker thread finished; awaiting finish of 1 more threads\n",
      "2017-06-29 10:36:19,858 : INFO : worker thread finished; awaiting finish of 0 more threads\n",
      "2017-06-29 10:36:19,858 : INFO : training on 20 raw words (0 effective words) took 0.0s, 0 effective words/s\n",
      "2017-06-29 10:36:19,859 : WARNING : under 10 jobs per worker: consider setting a smaller `batch_words' for smoother alpha decay\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# build the same model, making the 2 steps explicit\n",
    "new_model = gensim.models.Word2Vec(min_count=1)  # an empty model, no training\n",
    "new_model.build_vocab(sentences)                 # can be a non-repeatable, 1-pass generator     \n",
    "new_model.train(sentences, total_examples=new_model.corpus_count, epochs=new_model.iter)                       \n",
    "# can be a non-repeatable, 1-pass generator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Word2Vec(vocab=3, size=100, alpha=0.025)\n",
      "{'second': <gensim.models.keyedvectors.Vocab object at 0x7f1c573ce9d0>, 'first': <gensim.models.keyedvectors.Vocab object at 0x7f1c0d056b50>, 'sentence': <gensim.models.keyedvectors.Vocab object at 0x7f1c0d0569d0>}\n"
     ]
    }
   ],
   "source": [
    "print(new_model)\n",
    "print(model.wv.vocab)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### More data would be nice\n",
    "For the following examples, we'll use the [Lee Corpus](https://github.com/RaRe-Technologies/gensim/blob/develop/gensim/test/test_data/lee_background.cor) (which you already have if you've installed gensim):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Set file names for train and test data\n",
    "test_data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data']) + os.sep\n",
    "lee_train_file = test_data_dir + 'lee_background.cor'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<__main__.MyText object at 0x7f1c0cfe6a10>\n"
     ]
    }
   ],
   "source": [
    "class MyText(object):\n",
    "    def __iter__(self):\n",
    "        for line in open(lee_train_file):\n",
    "            # assume there's one document per line, tokens separated by whitespace\n",
    "            yield line.lower().split()\n",
    "\n",
    "sentences = MyText()\n",
    "\n",
    "print(sentences)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training\n",
    "`Word2Vec` accepts several parameters that affect both training speed and quality.\n",
    "\n",
    "### min_count\n",
    "`min_count` is for pruning the internal dictionary. Words that appear only once or twice in a billion-word corpus are probably uninteresting typos and garbage. In addition, there’s not enough data to make any meaningful training on those words, so it’s best to ignore them:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:22,567 : INFO : collecting all words and their counts\n",
      "2017-06-29 10:36:22,568 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n",
      "2017-06-29 10:36:22,599 : INFO : collected 10186 word types from a corpus of 59890 raw words and 300 sentences\n",
      "2017-06-29 10:36:22,601 : INFO : Loading a fresh vocabulary\n",
      "2017-06-29 10:36:22,613 : INFO : min_count=10 retains 806 unique words (7% of original 10186, drops 9380)\n",
      "2017-06-29 10:36:22,614 : INFO : min_count=10 leaves 40964 word corpus (68% of original 59890, drops 18926)\n",
      "2017-06-29 10:36:22,621 : INFO : deleting the raw counts dictionary of 10186 items\n",
      "2017-06-29 10:36:22,623 : INFO : sample=0.001 downsamples 54 most-common words\n",
      "2017-06-29 10:36:22,625 : INFO : downsampling leaves estimated 26224 word corpus (64.0% of prior 40964)\n",
      "2017-06-29 10:36:22,629 : INFO : estimated required memory for 806 words and 100 dimensions: 1047800 bytes\n",
      "2017-06-29 10:36:22,634 : INFO : resetting layer weights\n",
      "2017-06-29 10:36:22,651 : INFO : training model with 3 workers on 806 vocabulary and 100 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n",
      "2017-06-29 10:36:22,791 : INFO : worker thread finished; awaiting finish of 2 more threads\n",
      "2017-06-29 10:36:22,792 : INFO : worker thread finished; awaiting finish of 1 more threads\n",
      "2017-06-29 10:36:22,793 : INFO : worker thread finished; awaiting finish of 0 more threads\n",
      "2017-06-29 10:36:22,795 : INFO : training on 299450 raw words (130961 effective words) took 0.1s, 928696 effective words/s\n"
     ]
    }
   ],
   "source": [
    "# default value of min_count=5\n",
    "model = gensim.models.Word2Vec(sentences, min_count=10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### size\n",
    "`size` is the number of dimensions (N) of the N-dimensional space that gensim Word2Vec maps the words onto.\n",
    "\n",
    "Bigger size values require more training data, but can lead to better (more accurate) models. Reasonable values are in the tens to hundreds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:25,482 : INFO : collecting all words and their counts\n",
      "2017-06-29 10:36:25,484 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n",
      "2017-06-29 10:36:25,505 : INFO : collected 10186 word types from a corpus of 59890 raw words and 300 sentences\n",
      "2017-06-29 10:36:25,506 : INFO : Loading a fresh vocabulary\n",
      "2017-06-29 10:36:25,517 : INFO : min_count=5 retains 1723 unique words (16% of original 10186, drops 8463)\n",
      "2017-06-29 10:36:25,519 : INFO : min_count=5 leaves 46858 word corpus (78% of original 59890, drops 13032)\n",
      "2017-06-29 10:36:25,531 : INFO : deleting the raw counts dictionary of 10186 items\n",
      "2017-06-29 10:36:25,533 : INFO : sample=0.001 downsamples 49 most-common words\n",
      "2017-06-29 10:36:25,534 : INFO : downsampling leaves estimated 32849 word corpus (70.1% of prior 46858)\n",
      "2017-06-29 10:36:25,535 : INFO : estimated required memory for 1723 words and 200 dimensions: 3618300 bytes\n",
      "2017-06-29 10:36:25,542 : INFO : resetting layer weights\n",
      "2017-06-29 10:36:25,587 : INFO : training model with 3 workers on 1723 vocabulary and 200 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n",
      "2017-06-29 10:36:25,797 : INFO : worker thread finished; awaiting finish of 2 more threads\n",
      "2017-06-29 10:36:25,802 : INFO : worker thread finished; awaiting finish of 1 more threads\n",
      "2017-06-29 10:36:25,809 : INFO : worker thread finished; awaiting finish of 0 more threads\n",
      "2017-06-29 10:36:25,813 : INFO : training on 299450 raw words (164316 effective words) took 0.2s, 748937 effective words/s\n"
     ]
    }
   ],
   "source": [
    "# default value of size=100\n",
    "model = gensim.models.Word2Vec(sentences, size=200)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### workers\n",
    "`workers`, the last of the major parameters (full list [here](http://radimrehurek.com/gensim/models/word2vec.html#gensim.models.word2vec.Word2Vec)) is for training parallelization, to speed up training:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:27,068 : INFO : collecting all words and their counts\n",
      "2017-06-29 10:36:27,069 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n",
      "2017-06-29 10:36:27,090 : INFO : collected 10186 word types from a corpus of 59890 raw words and 300 sentences\n",
      "2017-06-29 10:36:27,091 : INFO : Loading a fresh vocabulary\n",
      "2017-06-29 10:36:27,109 : INFO : min_count=5 retains 1723 unique words (16% of original 10186, drops 8463)\n",
      "2017-06-29 10:36:27,110 : INFO : min_count=5 leaves 46858 word corpus (78% of original 59890, drops 13032)\n",
      "2017-06-29 10:36:27,118 : INFO : deleting the raw counts dictionary of 10186 items\n",
      "2017-06-29 10:36:27,122 : INFO : sample=0.001 downsamples 49 most-common words\n",
      "2017-06-29 10:36:27,123 : INFO : downsampling leaves estimated 32849 word corpus (70.1% of prior 46858)\n",
      "2017-06-29 10:36:27,125 : INFO : estimated required memory for 1723 words and 100 dimensions: 2239900 bytes\n",
      "2017-06-29 10:36:27,130 : INFO : resetting layer weights\n",
      "2017-06-29 10:36:27,162 : INFO : training model with 4 workers on 1723 vocabulary and 100 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n",
      "2017-06-29 10:36:27,323 : INFO : worker thread finished; awaiting finish of 3 more threads\n",
      "2017-06-29 10:36:27,325 : INFO : worker thread finished; awaiting finish of 2 more threads\n",
      "2017-06-29 10:36:27,330 : INFO : worker thread finished; awaiting finish of 1 more threads\n",
      "2017-06-29 10:36:27,331 : INFO : worker thread finished; awaiting finish of 0 more threads\n",
      "2017-06-29 10:36:27,334 : INFO : training on 299450 raw words (163999 effective words) took 0.2s, 963210 effective words/s\n",
      "2017-06-29 10:36:27,337 : WARNING : under 10 jobs per worker: consider setting a smaller `batch_words' for smoother alpha decay\n"
     ]
    }
   ],
   "source": [
    "# default value of workers=3 (tutorial says 1...)\n",
    "model = gensim.models.Word2Vec(sentences, workers=4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `workers` parameter only has an effect if you have [Cython](http://cython.org/) installed. Without Cython, you’ll only be able to use one core because of the [GIL](https://wiki.python.org/moin/GlobalInterpreterLock) (and `word2vec` training will be [miserably slow](http://rare-technologies.com/word2vec-in-python-part-two-optimizing/))."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Memory\n",
    "At its core, `word2vec` model parameters are stored as matrices (NumPy arrays). Each array is **#vocabulary** (controlled by min_count parameter) times **#size** (size parameter) of floats (single precision aka 4 bytes).\n",
    "\n",
    "Three such matrices are held in RAM (work is underway to reduce that number to two, or even one). So if your input contains 100,000 unique words, and you asked for layer `size=200`, the model will require approx. `100,000*200*4*3 bytes = ~229MB`.\n",
    "\n",
    "There’s a little extra memory needed for storing the vocabulary tree (100,000 words would take a few megabytes), but unless your words are extremely loooong strings, memory footprint will be dominated by the three matrices above."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluating\n",
    "`Word2Vec` training is an unsupervised task, there’s no good way to objectively evaluate the result. Evaluation depends on your end application.\n",
    "\n",
    "Google has released their testing set of about 20,000 syntactic and semantic test examples, following the “A is to B as C is to D” task. It is provided in the 'datasets' folder.\n",
    "\n",
    "For example a syntactic analogy of comparative type is bad:worse;good:?. There are total of 9 types of syntactic comparisons in the dataset like plural nouns and nouns of opposite meaning.\n",
    "\n",
    "The semantic questions contain five types of semantic analogies, such as capital cities (Paris:France;Tokyo:?) or family members (brother:sister;dad:?). "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Gensim supports the same evaluation set, in exactly the same format:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:30,524 : INFO : precomputing L2-norms of word weight vectors\n",
      "2017-06-29 10:36:30,529 : INFO : family: 0.0% (0/2)\n",
      "2017-06-29 10:36:30,583 : INFO : gram3-comparative: 0.0% (0/12)\n",
      "2017-06-29 10:36:30,618 : INFO : gram4-superlative: 0.0% (0/12)\n",
      "2017-06-29 10:36:30,653 : INFO : gram5-present-participle: 5.0% (1/20)\n",
      "2017-06-29 10:36:30,701 : INFO : gram6-nationality-adjective: 0.0% (0/20)\n",
      "2017-06-29 10:36:30,741 : INFO : gram7-past-tense: 0.0% (0/20)\n",
      "2017-06-29 10:36:30,781 : INFO : gram8-plural: 0.0% (0/12)\n",
      "2017-06-29 10:36:30,792 : INFO : total: 1.0% (1/98)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[{'correct': [], 'incorrect': [], 'section': u'capital-common-countries'},\n",
       " {'correct': [], 'incorrect': [], 'section': u'capital-world'},\n",
       " {'correct': [], 'incorrect': [], 'section': u'currency'},\n",
       " {'correct': [], 'incorrect': [], 'section': u'city-in-state'},\n",
       " {'correct': [],\n",
       "  'incorrect': [(u'HE', u'SHE', u'HIS', u'HER'),\n",
       "   (u'HIS', u'HER', u'HE', u'SHE')],\n",
       "  'section': u'family'},\n",
       " {'correct': [], 'incorrect': [], 'section': u'gram1-adjective-to-adverb'},\n",
       " {'correct': [], 'incorrect': [], 'section': u'gram2-opposite'},\n",
       " {'correct': [],\n",
       "  'incorrect': [(u'GOOD', u'BETTER', u'GREAT', u'GREATER'),\n",
       "   (u'GOOD', u'BETTER', u'LONG', u'LONGER'),\n",
       "   (u'GOOD', u'BETTER', u'LOW', u'LOWER'),\n",
       "   (u'GREAT', u'GREATER', u'LONG', u'LONGER'),\n",
       "   (u'GREAT', u'GREATER', u'LOW', u'LOWER'),\n",
       "   (u'GREAT', u'GREATER', u'GOOD', u'BETTER'),\n",
       "   (u'LONG', u'LONGER', u'LOW', u'LOWER'),\n",
       "   (u'LONG', u'LONGER', u'GOOD', u'BETTER'),\n",
       "   (u'LONG', u'LONGER', u'GREAT', u'GREATER'),\n",
       "   (u'LOW', u'LOWER', u'GOOD', u'BETTER'),\n",
       "   (u'LOW', u'LOWER', u'GREAT', u'GREATER'),\n",
       "   (u'LOW', u'LOWER', u'LONG', u'LONGER')],\n",
       "  'section': u'gram3-comparative'},\n",
       " {'correct': [],\n",
       "  'incorrect': [(u'BIG', u'BIGGEST', u'GOOD', u'BEST'),\n",
       "   (u'BIG', u'BIGGEST', u'GREAT', u'GREATEST'),\n",
       "   (u'BIG', u'BIGGEST', u'LARGE', u'LARGEST'),\n",
       "   (u'GOOD', u'BEST', u'GREAT', u'GREATEST'),\n",
       "   (u'GOOD', u'BEST', u'LARGE', u'LARGEST'),\n",
       "   (u'GOOD', u'BEST', u'BIG', u'BIGGEST'),\n",
       "   (u'GREAT', u'GREATEST', u'LARGE', u'LARGEST'),\n",
       "   (u'GREAT', u'GREATEST', u'BIG', u'BIGGEST'),\n",
       "   (u'GREAT', u'GREATEST', u'GOOD', u'BEST'),\n",
       "   (u'LARGE', u'LARGEST', u'BIG', u'BIGGEST'),\n",
       "   (u'LARGE', u'LARGEST', u'GOOD', u'BEST'),\n",
       "   (u'LARGE', u'LARGEST', u'GREAT', u'GREATEST')],\n",
       "  'section': u'gram4-superlative'},\n",
       " {'correct': [(u'LOOK', u'LOOKING', u'SAY', u'SAYING')],\n",
       "  'incorrect': [(u'GO', u'GOING', u'LOOK', u'LOOKING'),\n",
       "   (u'GO', u'GOING', u'PLAY', u'PLAYING'),\n",
       "   (u'GO', u'GOING', u'RUN', u'RUNNING'),\n",
       "   (u'GO', u'GOING', u'SAY', u'SAYING'),\n",
       "   (u'LOOK', u'LOOKING', u'PLAY', u'PLAYING'),\n",
       "   (u'LOOK', u'LOOKING', u'RUN', u'RUNNING'),\n",
       "   (u'LOOK', u'LOOKING', u'GO', u'GOING'),\n",
       "   (u'PLAY', u'PLAYING', u'RUN', u'RUNNING'),\n",
       "   (u'PLAY', u'PLAYING', u'SAY', u'SAYING'),\n",
       "   (u'PLAY', u'PLAYING', u'GO', u'GOING'),\n",
       "   (u'PLAY', u'PLAYING', u'LOOK', u'LOOKING'),\n",
       "   (u'RUN', u'RUNNING', u'SAY', u'SAYING'),\n",
       "   (u'RUN', u'RUNNING', u'GO', u'GOING'),\n",
       "   (u'RUN', u'RUNNING', u'LOOK', u'LOOKING'),\n",
       "   (u'RUN', u'RUNNING', u'PLAY', u'PLAYING'),\n",
       "   (u'SAY', u'SAYING', u'GO', u'GOING'),\n",
       "   (u'SAY', u'SAYING', u'LOOK', u'LOOKING'),\n",
       "   (u'SAY', u'SAYING', u'PLAY', u'PLAYING'),\n",
       "   (u'SAY', u'SAYING', u'RUN', u'RUNNING')],\n",
       "  'section': u'gram5-present-participle'},\n",
       " {'correct': [],\n",
       "  'incorrect': [(u'AUSTRALIA', u'AUSTRALIAN', u'FRANCE', u'FRENCH'),\n",
       "   (u'AUSTRALIA', u'AUSTRALIAN', u'INDIA', u'INDIAN'),\n",
       "   (u'AUSTRALIA', u'AUSTRALIAN', u'ISRAEL', u'ISRAELI'),\n",
       "   (u'AUSTRALIA', u'AUSTRALIAN', u'SWITZERLAND', u'SWISS'),\n",
       "   (u'FRANCE', u'FRENCH', u'INDIA', u'INDIAN'),\n",
       "   (u'FRANCE', u'FRENCH', u'ISRAEL', u'ISRAELI'),\n",
       "   (u'FRANCE', u'FRENCH', u'SWITZERLAND', u'SWISS'),\n",
       "   (u'FRANCE', u'FRENCH', u'AUSTRALIA', u'AUSTRALIAN'),\n",
       "   (u'INDIA', u'INDIAN', u'ISRAEL', u'ISRAELI'),\n",
       "   (u'INDIA', u'INDIAN', u'SWITZERLAND', u'SWISS'),\n",
       "   (u'INDIA', u'INDIAN', u'AUSTRALIA', u'AUSTRALIAN'),\n",
       "   (u'INDIA', u'INDIAN', u'FRANCE', u'FRENCH'),\n",
       "   (u'ISRAEL', u'ISRAELI', u'SWITZERLAND', u'SWISS'),\n",
       "   (u'ISRAEL', u'ISRAELI', u'AUSTRALIA', u'AUSTRALIAN'),\n",
       "   (u'ISRAEL', u'ISRAELI', u'FRANCE', u'FRENCH'),\n",
       "   (u'ISRAEL', u'ISRAELI', u'INDIA', u'INDIAN'),\n",
       "   (u'SWITZERLAND', u'SWISS', u'AUSTRALIA', u'AUSTRALIAN'),\n",
       "   (u'SWITZERLAND', u'SWISS', u'FRANCE', u'FRENCH'),\n",
       "   (u'SWITZERLAND', u'SWISS', u'INDIA', u'INDIAN'),\n",
       "   (u'SWITZERLAND', u'SWISS', u'ISRAEL', u'ISRAELI')],\n",
       "  'section': u'gram6-nationality-adjective'},\n",
       " {'correct': [],\n",
       "  'incorrect': [(u'GOING', u'WENT', u'PAYING', u'PAID'),\n",
       "   (u'GOING', u'WENT', u'PLAYING', u'PLAYED'),\n",
       "   (u'GOING', u'WENT', u'SAYING', u'SAID'),\n",
       "   (u'GOING', u'WENT', u'TAKING', u'TOOK'),\n",
       "   (u'PAYING', u'PAID', u'PLAYING', u'PLAYED'),\n",
       "   (u'PAYING', u'PAID', u'SAYING', u'SAID'),\n",
       "   (u'PAYING', u'PAID', u'TAKING', u'TOOK'),\n",
       "   (u'PAYING', u'PAID', u'GOING', u'WENT'),\n",
       "   (u'PLAYING', u'PLAYED', u'SAYING', u'SAID'),\n",
       "   (u'PLAYING', u'PLAYED', u'TAKING', u'TOOK'),\n",
       "   (u'PLAYING', u'PLAYED', u'GOING', u'WENT'),\n",
       "   (u'PLAYING', u'PLAYED', u'PAYING', u'PAID'),\n",
       "   (u'SAYING', u'SAID', u'TAKING', u'TOOK'),\n",
       "   (u'SAYING', u'SAID', u'GOING', u'WENT'),\n",
       "   (u'SAYING', u'SAID', u'PAYING', u'PAID'),\n",
       "   (u'SAYING', u'SAID', u'PLAYING', u'PLAYED'),\n",
       "   (u'TAKING', u'TOOK', u'GOING', u'WENT'),\n",
       "   (u'TAKING', u'TOOK', u'PAYING', u'PAID'),\n",
       "   (u'TAKING', u'TOOK', u'PLAYING', u'PLAYED'),\n",
       "   (u'TAKING', u'TOOK', u'SAYING', u'SAID')],\n",
       "  'section': u'gram7-past-tense'},\n",
       " {'correct': [],\n",
       "  'incorrect': [(u'BUILDING', u'BUILDINGS', u'CAR', u'CARS'),\n",
       "   (u'BUILDING', u'BUILDINGS', u'CHILD', u'CHILDREN'),\n",
       "   (u'BUILDING', u'BUILDINGS', u'MAN', u'MEN'),\n",
       "   (u'CAR', u'CARS', u'CHILD', u'CHILDREN'),\n",
       "   (u'CAR', u'CARS', u'MAN', u'MEN'),\n",
       "   (u'CAR', u'CARS', u'BUILDING', u'BUILDINGS'),\n",
       "   (u'CHILD', u'CHILDREN', u'MAN', u'MEN'),\n",
       "   (u'CHILD', u'CHILDREN', u'BUILDING', u'BUILDINGS'),\n",
       "   (u'CHILD', u'CHILDREN', u'CAR', u'CARS'),\n",
       "   (u'MAN', u'MEN', u'BUILDING', u'BUILDINGS'),\n",
       "   (u'MAN', u'MEN', u'CAR', u'CARS'),\n",
       "   (u'MAN', u'MEN', u'CHILD', u'CHILDREN')],\n",
       "  'section': u'gram8-plural'},\n",
       " {'correct': [], 'incorrect': [], 'section': u'gram9-plural-verbs'},\n",
       " {'correct': [(u'LOOK', u'LOOKING', u'SAY', u'SAYING')],\n",
       "  'incorrect': [(u'HE', u'SHE', u'HIS', u'HER'),\n",
       "   (u'HIS', u'HER', u'HE', u'SHE'),\n",
       "   (u'GOOD', u'BETTER', u'GREAT', u'GREATER'),\n",
       "   (u'GOOD', u'BETTER', u'LONG', u'LONGER'),\n",
       "   (u'GOOD', u'BETTER', u'LOW', u'LOWER'),\n",
       "   (u'GREAT', u'GREATER', u'LONG', u'LONGER'),\n",
       "   (u'GREAT', u'GREATER', u'LOW', u'LOWER'),\n",
       "   (u'GREAT', u'GREATER', u'GOOD', u'BETTER'),\n",
       "   (u'LONG', u'LONGER', u'LOW', u'LOWER'),\n",
       "   (u'LONG', u'LONGER', u'GOOD', u'BETTER'),\n",
       "   (u'LONG', u'LONGER', u'GREAT', u'GREATER'),\n",
       "   (u'LOW', u'LOWER', u'GOOD', u'BETTER'),\n",
       "   (u'LOW', u'LOWER', u'GREAT', u'GREATER'),\n",
       "   (u'LOW', u'LOWER', u'LONG', u'LONGER'),\n",
       "   (u'BIG', u'BIGGEST', u'GOOD', u'BEST'),\n",
       "   (u'BIG', u'BIGGEST', u'GREAT', u'GREATEST'),\n",
       "   (u'BIG', u'BIGGEST', u'LARGE', u'LARGEST'),\n",
       "   (u'GOOD', u'BEST', u'GREAT', u'GREATEST'),\n",
       "   (u'GOOD', u'BEST', u'LARGE', u'LARGEST'),\n",
       "   (u'GOOD', u'BEST', u'BIG', u'BIGGEST'),\n",
       "   (u'GREAT', u'GREATEST', u'LARGE', u'LARGEST'),\n",
       "   (u'GREAT', u'GREATEST', u'BIG', u'BIGGEST'),\n",
       "   (u'GREAT', u'GREATEST', u'GOOD', u'BEST'),\n",
       "   (u'LARGE', u'LARGEST', u'BIG', u'BIGGEST'),\n",
       "   (u'LARGE', u'LARGEST', u'GOOD', u'BEST'),\n",
       "   (u'LARGE', u'LARGEST', u'GREAT', u'GREATEST'),\n",
       "   (u'GO', u'GOING', u'LOOK', u'LOOKING'),\n",
       "   (u'GO', u'GOING', u'PLAY', u'PLAYING'),\n",
       "   (u'GO', u'GOING', u'RUN', u'RUNNING'),\n",
       "   (u'GO', u'GOING', u'SAY', u'SAYING'),\n",
       "   (u'LOOK', u'LOOKING', u'PLAY', u'PLAYING'),\n",
       "   (u'LOOK', u'LOOKING', u'RUN', u'RUNNING'),\n",
       "   (u'LOOK', u'LOOKING', u'GO', u'GOING'),\n",
       "   (u'PLAY', u'PLAYING', u'RUN', u'RUNNING'),\n",
       "   (u'PLAY', u'PLAYING', u'SAY', u'SAYING'),\n",
       "   (u'PLAY', u'PLAYING', u'GO', u'GOING'),\n",
       "   (u'PLAY', u'PLAYING', u'LOOK', u'LOOKING'),\n",
       "   (u'RUN', u'RUNNING', u'SAY', u'SAYING'),\n",
       "   (u'RUN', u'RUNNING', u'GO', u'GOING'),\n",
       "   (u'RUN', u'RUNNING', u'LOOK', u'LOOKING'),\n",
       "   (u'RUN', u'RUNNING', u'PLAY', u'PLAYING'),\n",
       "   (u'SAY', u'SAYING', u'GO', u'GOING'),\n",
       "   (u'SAY', u'SAYING', u'LOOK', u'LOOKING'),\n",
       "   (u'SAY', u'SAYING', u'PLAY', u'PLAYING'),\n",
       "   (u'SAY', u'SAYING', u'RUN', u'RUNNING'),\n",
       "   (u'AUSTRALIA', u'AUSTRALIAN', u'FRANCE', u'FRENCH'),\n",
       "   (u'AUSTRALIA', u'AUSTRALIAN', u'INDIA', u'INDIAN'),\n",
       "   (u'AUSTRALIA', u'AUSTRALIAN', u'ISRAEL', u'ISRAELI'),\n",
       "   (u'AUSTRALIA', u'AUSTRALIAN', u'SWITZERLAND', u'SWISS'),\n",
       "   (u'FRANCE', u'FRENCH', u'INDIA', u'INDIAN'),\n",
       "   (u'FRANCE', u'FRENCH', u'ISRAEL', u'ISRAELI'),\n",
       "   (u'FRANCE', u'FRENCH', u'SWITZERLAND', u'SWISS'),\n",
       "   (u'FRANCE', u'FRENCH', u'AUSTRALIA', u'AUSTRALIAN'),\n",
       "   (u'INDIA', u'INDIAN', u'ISRAEL', u'ISRAELI'),\n",
       "   (u'INDIA', u'INDIAN', u'SWITZERLAND', u'SWISS'),\n",
       "   (u'INDIA', u'INDIAN', u'AUSTRALIA', u'AUSTRALIAN'),\n",
       "   (u'INDIA', u'INDIAN', u'FRANCE', u'FRENCH'),\n",
       "   (u'ISRAEL', u'ISRAELI', u'SWITZERLAND', u'SWISS'),\n",
       "   (u'ISRAEL', u'ISRAELI', u'AUSTRALIA', u'AUSTRALIAN'),\n",
       "   (u'ISRAEL', u'ISRAELI', u'FRANCE', u'FRENCH'),\n",
       "   (u'ISRAEL', u'ISRAELI', u'INDIA', u'INDIAN'),\n",
       "   (u'SWITZERLAND', u'SWISS', u'AUSTRALIA', u'AUSTRALIAN'),\n",
       "   (u'SWITZERLAND', u'SWISS', u'FRANCE', u'FRENCH'),\n",
       "   (u'SWITZERLAND', u'SWISS', u'INDIA', u'INDIAN'),\n",
       "   (u'SWITZERLAND', u'SWISS', u'ISRAEL', u'ISRAELI'),\n",
       "   (u'GOING', u'WENT', u'PAYING', u'PAID'),\n",
       "   (u'GOING', u'WENT', u'PLAYING', u'PLAYED'),\n",
       "   (u'GOING', u'WENT', u'SAYING', u'SAID'),\n",
       "   (u'GOING', u'WENT', u'TAKING', u'TOOK'),\n",
       "   (u'PAYING', u'PAID', u'PLAYING', u'PLAYED'),\n",
       "   (u'PAYING', u'PAID', u'SAYING', u'SAID'),\n",
       "   (u'PAYING', u'PAID', u'TAKING', u'TOOK'),\n",
       "   (u'PAYING', u'PAID', u'GOING', u'WENT'),\n",
       "   (u'PLAYING', u'PLAYED', u'SAYING', u'SAID'),\n",
       "   (u'PLAYING', u'PLAYED', u'TAKING', u'TOOK'),\n",
       "   (u'PLAYING', u'PLAYED', u'GOING', u'WENT'),\n",
       "   (u'PLAYING', u'PLAYED', u'PAYING', u'PAID'),\n",
       "   (u'SAYING', u'SAID', u'TAKING', u'TOOK'),\n",
       "   (u'SAYING', u'SAID', u'GOING', u'WENT'),\n",
       "   (u'SAYING', u'SAID', u'PAYING', u'PAID'),\n",
       "   (u'SAYING', u'SAID', u'PLAYING', u'PLAYED'),\n",
       "   (u'TAKING', u'TOOK', u'GOING', u'WENT'),\n",
       "   (u'TAKING', u'TOOK', u'PAYING', u'PAID'),\n",
       "   (u'TAKING', u'TOOK', u'PLAYING', u'PLAYED'),\n",
       "   (u'TAKING', u'TOOK', u'SAYING', u'SAID'),\n",
       "   (u'BUILDING', u'BUILDINGS', u'CAR', u'CARS'),\n",
       "   (u'BUILDING', u'BUILDINGS', u'CHILD', u'CHILDREN'),\n",
       "   (u'BUILDING', u'BUILDINGS', u'MAN', u'MEN'),\n",
       "   (u'CAR', u'CARS', u'CHILD', u'CHILDREN'),\n",
       "   (u'CAR', u'CARS', u'MAN', u'MEN'),\n",
       "   (u'CAR', u'CARS', u'BUILDING', u'BUILDINGS'),\n",
       "   (u'CHILD', u'CHILDREN', u'MAN', u'MEN'),\n",
       "   (u'CHILD', u'CHILDREN', u'BUILDING', u'BUILDINGS'),\n",
       "   (u'CHILD', u'CHILDREN', u'CAR', u'CARS'),\n",
       "   (u'MAN', u'MEN', u'BUILDING', u'BUILDINGS'),\n",
       "   (u'MAN', u'MEN', u'CAR', u'CARS'),\n",
       "   (u'MAN', u'MEN', u'CHILD', u'CHILDREN')],\n",
       "  'section': 'total'}]"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.accuracy('./datasets/questions-words.txt')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This `accuracy` takes an \n",
    "[optional parameter](http://radimrehurek.com/gensim/models/word2vec.html#gensim.models.word2vec.Word2Vec.accuracy) `restrict_vocab` \n",
    "which limits which test examples are to be considered.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the December 2016 release of Gensim we added a better way to evaluate semantic similarity.\n",
    "\n",
    "By default it uses an academic dataset WS-353 but one can create a dataset specific to your business based on it. It contains word pairs together with human-assigned similarity judgments. It measures the relatedness or co-occurrence of two words. For example, 'coast' and 'shore' are very similar as they appear in the same context. At the same time 'clothes' and 'closet' are less similar because they are related but not interchangeable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:32,406 : INFO : Pearson correlation coefficient against /home/chinmaya/GSOC/Gensim/gensim/gensim/test/test_data/wordsim353.tsv: 0.1480\n",
      "2017-06-29 10:36:32,407 : INFO : Spearman rank-order correlation coefficient against /home/chinmaya/GSOC/Gensim/gensim/gensim/test/test_data/wordsim353.tsv: 0.1820\n",
      "2017-06-29 10:36:32,408 : INFO : Pairs with unknown words ratio: 85.6%\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "((0.14802303571188502, 0.29991609812618542),\n",
       " SpearmanrResult(correlation=0.18196628619816893, pvalue=0.20125520403388769),\n",
       " 85.55240793201133)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.evaluate_word_pairs(test_data_dir + 'wordsim353.tsv')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Once again, **good performance on Google's or WS-353 test set doesn’t mean word2vec will work well in your application, or vice versa**. It’s always best to evaluate directly on your intended task. For an example of how to use word2vec in a classifier pipeline, see this [tutorial](https://github.com/RaRe-Technologies/movie-plots-by-genre)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Storing and loading models\n",
    "You can store/load models using the standard gensim methods:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:33,533 : INFO : saving Word2Vec object under /tmp/tmpNVnhzsgensim_temp, separately None\n",
      "2017-06-29 10:36:33,535 : INFO : not storing attribute syn0norm\n",
      "2017-06-29 10:36:33,535 : INFO : not storing attribute cum_table\n",
      "2017-06-29 10:36:33,550 : INFO : saved /tmp/tmpNVnhzsgensim_temp\n"
     ]
    }
   ],
   "source": [
    "from tempfile import mkstemp\n",
    "\n",
    "fs, temp_path = mkstemp(\"gensim_temp\")  # creates a temp file\n",
    "\n",
    "model.save(temp_path)  # save the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:34,033 : INFO : loading Word2Vec object from /tmp/tmpNVnhzsgensim_temp\n",
      "2017-06-29 10:36:34,041 : INFO : loading wv recursively from /tmp/tmpNVnhzsgensim_temp.wv.* with mmap=None\n",
      "2017-06-29 10:36:34,042 : INFO : setting ignored attribute syn0norm to None\n",
      "2017-06-29 10:36:34,044 : INFO : setting ignored attribute cum_table to None\n",
      "2017-06-29 10:36:34,048 : INFO : loaded /tmp/tmpNVnhzsgensim_temp\n"
     ]
    }
   ],
   "source": [
    "new_model = gensim.models.Word2Vec.load(temp_path)  # open the model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "which uses pickle internally, optionally `mmap`‘ing the model’s internal large NumPy matrices into virtual memory directly from disk files, for inter-process memory sharing.\n",
    "\n",
    "In addition, you can load models created by the original C tool, both using its text and binary formats:\n",
    "```\n",
    "  model = gensim.models.KeyedVectors.load_word2vec_format('/tmp/vectors.txt', binary=False)\n",
    "  # using gzipped/bz2 input works too, no need to unzip:\n",
    "  model = gensim.models.KeyedVectors.load_word2vec_format('/tmp/vectors.bin.gz', binary=True)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Online training / Resuming training\n",
    "Advanced users can load a model and continue training it with more sentences and [new vocabulary words](online_w2v_tutorial.ipynb):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:35,557 : INFO : loading Word2Vec object from /tmp/tmpNVnhzsgensim_temp\n",
      "2017-06-29 10:36:35,566 : INFO : loading wv recursively from /tmp/tmpNVnhzsgensim_temp.wv.* with mmap=None\n",
      "2017-06-29 10:36:35,567 : INFO : setting ignored attribute syn0norm to None\n",
      "2017-06-29 10:36:35,572 : INFO : setting ignored attribute cum_table to None\n",
      "2017-06-29 10:36:35,573 : INFO : loaded /tmp/tmpNVnhzsgensim_temp\n",
      "2017-06-29 10:36:35,581 : INFO : collecting all words and their counts\n",
      "2017-06-29 10:36:35,582 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n",
      "2017-06-29 10:36:35,586 : INFO : collected 13 word types from a corpus of 13 raw words and 1 sentences\n",
      "2017-06-29 10:36:35,587 : INFO : Updating model with new vocabulary\n",
      "2017-06-29 10:36:35,589 : INFO : New added 0 unique words (0% of original 13)\n",
      "                        and increased the count of 0 pre-existing words (0% of original 13)\n",
      "2017-06-29 10:36:35,590 : INFO : deleting the raw counts dictionary of 13 items\n",
      "2017-06-29 10:36:35,591 : INFO : sample=0.001 downsamples 0 most-common words\n",
      "2017-06-29 10:36:35,592 : INFO : downsampling leaves estimated 0 word corpus (0.0% of prior 0)\n",
      "2017-06-29 10:36:35,594 : INFO : estimated required memory for 1723 words and 100 dimensions: 2239900 bytes\n",
      "2017-06-29 10:36:35,599 : INFO : updating layer weights\n",
      "2017-06-29 10:36:35,601 : INFO : training model with 4 workers on 1723 vocabulary and 100 features, using sg=0 hs=0 sample=0.001 negative=5 window=5\n",
      "2017-06-29 10:36:35,606 : INFO : worker thread finished; awaiting finish of 3 more threads\n",
      "2017-06-29 10:36:35,607 : INFO : worker thread finished; awaiting finish of 2 more threads\n",
      "2017-06-29 10:36:35,609 : INFO : worker thread finished; awaiting finish of 1 more threads\n",
      "2017-06-29 10:36:35,613 : INFO : worker thread finished; awaiting finish of 0 more threads\n",
      "2017-06-29 10:36:35,614 : INFO : training on 65 raw words (28 effective words) took 0.0s, 3413 effective words/s\n",
      "2017-06-29 10:36:35,615 : WARNING : under 10 jobs per worker: consider setting a smaller `batch_words' for smoother alpha decay\n"
     ]
    }
   ],
   "source": [
    "model = gensim.models.Word2Vec.load(temp_path)\n",
    "more_sentences = [['Advanced', 'users', 'can', 'load', 'a', 'model', 'and', 'continue', 'training', 'it', 'with', 'more', 'sentences']]\n",
    "model.build_vocab(more_sentences, update=True)\n",
    "model.train(more_sentences, total_examples=model.corpus_count, epochs=model.iter)\n",
    "\n",
    "# cleaning up temp\n",
    "os.close(fs)\n",
    "os.remove(temp_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You may need to tweak the `total_words` parameter to `train()`, depending on what learning rate decay you want to simulate.\n",
    "\n",
    "Note that it’s not possible to resume training with models generated by the C tool, `KeyedVectors.load_word2vec_format()`. You can still use them for querying/similarity, but information vital for training (the vocab tree) is missing there.\n",
    "\n",
    "## Using the model\n",
    "`Word2Vec` supports several word similarity tasks out of the box:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:36,558 : INFO : precomputing L2-norms of word weight vectors\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[('longer', 0.9916001558303833)]"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.most_similar(positive=['human', 'crime'], negative=['party'], topn=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:37,587 : WARNING : vectors for words set(['lunch', 'input', 'cat']) are not present in the model, ignoring these words\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'sentence'"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.doesnt_match(\"input is lunch he sentence cat\".split())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.99914980326\n",
      "0.995203599363\n"
     ]
    }
   ],
   "source": [
    "print(model.similarity('human', 'party'))\n",
    "print(model.similarity('tree', 'murder'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can get the probability distribution for the center word given the context words as input:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('more', 0.0010031241), ('can', 0.00092728506), ('continue', 0.00087752187), ('training', 0.00080867682), ('there', 0.00075810013), ('three', 0.00075742434), ('australia', 0.00075092859), ('government', 0.0007505166), ('their', 0.00074284436), ('us', 0.00073618308)]\n"
     ]
    }
   ],
   "source": [
    "print(model.predict_output_word(['emergency', 'beacon', 'received']))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The results here don't look good because the training corpus is very small. To get meaningful results one needs to train on 500k+ words."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you need the raw output vectors in your application, you can access these either on a word-by-word basis:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.00313283,  0.02270725, -0.0271953 , -0.00758541, -0.03084832,\n",
       "       -0.03540374,  0.00492509, -0.08605313, -0.00946797, -0.01907749,\n",
       "        0.0190183 , -0.02690557, -0.0665649 , -0.01858037, -0.02188841,\n",
       "        0.04523174, -0.03034727, -0.00294408,  0.02323552, -0.02585541,\n",
       "       -0.06424622, -0.00719615,  0.06513051,  0.04760417,  0.02894664,\n",
       "        0.01104737, -0.00513022,  0.01997521, -0.0142725 ,  0.00513998,\n",
       "        0.00099208,  0.07234117,  0.01262072, -0.00151589,  0.02293177,\n",
       "        0.02008283, -0.03751098,  0.01848946,  0.01339256, -0.06704903,\n",
       "       -0.07547309,  0.00120684, -0.04351105, -0.02421799,  0.03180883,\n",
       "       -0.05489816,  0.03536329,  0.00560333, -0.01004709,  0.04278436,\n",
       "        0.01327703,  0.00862974, -0.03693489,  0.01097009,  0.01643447,\n",
       "       -0.01702741,  0.05618335, -0.03153885,  0.02427759, -0.03469121,\n",
       "       -0.03066109, -0.05092006,  0.01682321, -0.03714861, -0.00944941,\n",
       "       -0.06158038, -0.08220627,  0.03865834,  0.05205975, -0.00297223,\n",
       "       -0.00764436,  0.00625849, -0.04550754,  0.01111075, -0.04805974,\n",
       "       -0.05271595,  0.03614397, -0.01115665,  0.04689607,  0.04113698,\n",
       "       -0.01792447,  0.03566624, -0.01676619,  0.00202644,  0.01494004,\n",
       "        0.00792563, -0.08858279, -0.08187189,  0.0634894 , -0.02159132,\n",
       "       -0.05633228, -0.04459627, -0.04756012, -0.0024067 , -0.02443214,\n",
       "       -0.02618414, -0.0249261 ,  0.02130016, -0.05084078,  0.00092178], dtype=float32)"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model['tree']  # raw NumPy vector of a word"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "…or en-masse as a 2D NumPy matrix from `model.wv.syn0`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training Loss Computation\n",
    "\n",
    "The parameter `compute_loss` can be used to toggle computation of loss while training the Word2Vec model. The computed loss is stored in the model attribute `running_training_loss` and can be retrieved using the function `get_latest_training_loss` as follows : "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2017-06-29 10:36:42,297 : INFO : collecting all words and their counts\n",
      "2017-06-29 10:36:42,300 : INFO : PROGRESS: at sentence #0, processed 0 words, keeping 0 word types\n",
      "2017-06-29 10:36:42,333 : INFO : collected 10186 word types from a corpus of 59890 raw words and 300 sentences\n",
      "2017-06-29 10:36:42,335 : INFO : Loading a fresh vocabulary\n",
      "2017-06-29 10:36:42,372 : INFO : min_count=1 retains 10186 unique words (100% of original 10186, drops 0)\n",
      "2017-06-29 10:36:42,372 : INFO : min_count=1 leaves 59890 word corpus (100% of original 59890, drops 0)\n",
      "2017-06-29 10:36:42,406 : INFO : deleting the raw counts dictionary of 10186 items\n",
      "2017-06-29 10:36:42,407 : INFO : sample=0.001 downsamples 37 most-common words\n",
      "2017-06-29 10:36:42,408 : INFO : downsampling leaves estimated 47231 word corpus (78.9% of prior 59890)\n",
      "2017-06-29 10:36:42,409 : INFO : estimated required memory for 10186 words and 100 dimensions: 13241800 bytes\n",
      "2017-06-29 10:36:42,452 : INFO : resetting layer weights\n",
      "2017-06-29 10:36:42,568 : INFO : training model with 3 workers on 10186 vocabulary and 100 features, using sg=1 hs=0 sample=0.001 negative=5 window=5\n",
      "2017-06-29 10:36:43,357 : INFO : worker thread finished; awaiting finish of 2 more threads\n",
      "2017-06-29 10:36:43,369 : INFO : worker thread finished; awaiting finish of 1 more threads\n",
      "2017-06-29 10:36:43,392 : INFO : worker thread finished; awaiting finish of 0 more threads\n",
      "2017-06-29 10:36:43,393 : INFO : training on 299450 raw words (235935 effective words) took 0.8s, 286433 effective words/s\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1348399.25\n"
     ]
    }
   ],
   "source": [
    "# instantiating and training the Word2Vec model\n",
    "model_with_loss = gensim.models.Word2Vec(sentences, min_count=1, compute_loss=True, hs=0, sg=1, seed=42)\n",
    "\n",
    "# getting the training loss value\n",
    "training_loss = model_with_loss.get_latest_training_loss()\n",
    "print(training_loss)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Benchmarks to see effect of training loss compuation code on training time\n",
    "\n",
    "We first download and setup the test data used for getting the benchmarks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['/home/chinmaya/GSOC/Gensim/gensim/docs/notebooks/../../gensim/test/test_data/lee_background.cor', '/home/chinmaya/GSOC/Gensim/gensim/docs/notebooks/text8_1000000', '/home/chinmaya/GSOC/Gensim/gensim/docs/notebooks/text8_10000000', '/home/chinmaya/GSOC/Gensim/gensim/docs/notebooks/text8_50000000', '/home/chinmaya/GSOC/Gensim/gensim/docs/notebooks/text8']\n"
     ]
    }
   ],
   "source": [
    "input_data_files = []\n",
    "\n",
    "def setup_input_data():\n",
    "    # check if test data already present\n",
    "    if os.path.isfile('./text8') is False:\n",
    "\n",
    "        # download and decompress 'text8' corpus\n",
    "        import zipfile\n",
    "        ! wget 'http://mattmahoney.net/dc/text8.zip'\n",
    "        ! unzip 'text8.zip'\n",
    "    \n",
    "        # create 1 MB, 10 MB and 50 MB files\n",
    "        ! head -c1000000 text8 > text8_1000000\n",
    "        ! head -c10000000 text8 > text8_10000000\n",
    "        ! head -c50000000 text8 > text8_50000000\n",
    "                \n",
    "    # add 25 KB test file\n",
    "    input_data_files.append(os.path.join(os.getcwd(), '../../gensim/test/test_data/lee_background.cor'))\n",
    "\n",
    "    # add 1 MB test file\n",
    "    input_data_files.append(os.path.join(os.getcwd(), 'text8_1000000'))\n",
    "\n",
    "    # add 10 MB test file\n",
    "    input_data_files.append(os.path.join(os.getcwd(), 'text8_10000000'))\n",
    "\n",
    "    # add 50 MB test file\n",
    "    input_data_files.append(os.path.join(os.getcwd(), 'text8_50000000'))\n",
    "\n",
    "    # add 100 MB test file\n",
    "    input_data_files.append(os.path.join(os.getcwd(), 'text8'))\n",
    "\n",
    "setup_input_data()\n",
    "print(input_data_files)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now compare the training time taken for different combinations of input data and model training parameters like `hs` and `sg`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['/home/chinmaya/GSOC/Gensim/gensim/docs/notebooks/../../gensim/test/test_data/lee_background.cor', '/home/chinmaya/GSOC/Gensim/gensim/docs/notebooks/text8_50000000']\n",
      "    compute_loss  hs        mean  sg       std  \\\n",
      "12          True   0  125.242767   1  0.442522   \n",
      "13         False   0  124.090732   1  0.432895   \n",
      "14          True   1  252.800164   1  1.140344   \n",
      "15         False   1  245.065643   1  2.657392   \n",
      "8           True   0   43.812430   0  1.216697   \n",
      "9          False   0   42.815214   0  0.142814   \n",
      "10          True   1   74.801153   0  0.300728   \n",
      "11         False   1   74.236441   0  0.126426   \n",
      "4           True   0    0.560387   1  0.005805   \n",
      "5          False   0    0.687179   1  0.143629   \n",
      "6           True   1    1.126855   1  0.004407   \n",
      "7          False   1    1.135358   1  0.059161   \n",
      "0           True   0    0.316948   0  0.005148   \n",
      "1          False   0    0.319236   0  0.005792   \n",
      "2           True   1    0.429879   0  0.005373   \n",
      "3          False   1    0.429489   0  0.000756   \n",
      "\n",
      "                                           train_data  \n",
      "12  /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "13  /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "14  /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "15  /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "8   /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "9   /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "10  /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "11  /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "4   /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "5   /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "6   /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "7   /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "0   /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "1   /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "2   /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n",
      "3   /home/chinmaya/GSOC/Gensim/gensim/docs/noteboo...  \n"
     ]
    }
   ],
   "source": [
    "# using 25 KB and 50 MB files only for generating o/p -> comment next line for using all 5 test files\n",
    "input_data_files = [input_data_files[0], input_data_files[-2]]\n",
    "print(input_data_files)\n",
    "\n",
    "import time\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "train_time_values = []\n",
    "seed_val = 42\n",
    "sg_values = [0, 1]\n",
    "hs_values = [0, 1]\n",
    "\n",
    "for data_file in input_data_files:\n",
    "    data = gensim.models.word2vec.LineSentence(data_file) \n",
    "    for sg_val in sg_values:\n",
    "        for hs_val in hs_values:\n",
    "            for loss_flag in [True, False]:\n",
    "                time_taken_list = []\n",
    "                for i in range(3):\n",
    "                    start_time = time.time()\n",
    "                    w2v_model = gensim.models.Word2Vec(data, compute_loss=loss_flag, sg=sg_val, hs=hs_val, seed=seed_val) \n",
    "                    time_taken_list.append(time.time() - start_time)\n",
    "\n",
    "                time_taken_list = np.array(time_taken_list)\n",
    "                time_mean = np.mean(time_taken_list)\n",
    "                time_std = np.std(time_taken_list)\n",
    "                train_time_values.append({'train_data': data_file, 'compute_loss': loss_flag, 'sg': sg_val, 'hs': hs_val, 'mean': time_mean, 'std': time_std})\n",
    "\n",
    "train_times_table = pd.DataFrame(train_time_values)\n",
    "train_times_table = train_times_table.sort_values(by=['train_data', 'sg', 'hs', 'compute_loss'], ascending=[False, False, True, False])\n",
    "print(train_times_table)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "In this tutorial we learned how to train word2vec models on your custom data and also how to evaluate it. Hope that you too will find this popular tool useful in your Machine Learning tasks!\n",
    "\n",
    "## Links\n",
    "\n",
    "\n",
    "Full `word2vec` API docs [here](http://radimrehurek.com/gensim/models/word2vec.html); get [gensim](http://radimrehurek.com/gensim/) here. Original C toolkit and `word2vec` papers by Google [here](https://code.google.com/archive/p/word2vec/)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
